import { create } from "zustand";
import type { StateCreator } from "zustand";
import { immer } from "zustand/middleware/immer";
import {
  devtools,
  persist,
  subscribeWithSelector,
  createJSONStorage,
} from "zustand/middleware";
import { createSelectors } from "@/utils/createSelectors";
import dayjs from "dayjs";

const defaultConfig = {
  autoCheckUpdate: true,
  multiCutHotkey: "PAGEDOWN",
  singleCutHotkey: "PAGEUP",
  mouseCutHotkey: "DELETE",
  scriptStartHotkey: "F10",
  scriptStopHotkey: "F11",
};

/** ---------------state start--------------- */
const initState = {
  // 偏好设置初始值
  initSetting: true, // 是否初始化偏好设置(读了配置文件)
  config: { ...defaultConfig },
};
/** ---------------state end--------------- */

/** ---------------方法start--------------- */

/** ---------------方法end--------------- */

const createConfigSlice: StateCreator<
  typeof initState,
  [
    ["zustand/immer", never],
    ["zustand/devtools", unknown],
    ["zustand/subscribeWithSelector", never],
    ["zustand/persist", unknown]
  ]
> = () => initState;

export const useConfigStore = createSelectors(
  create<typeof initState>()(
    immer(
      devtools(
        subscribeWithSelector(
          persist(createConfigSlice, {
            // 存储名称(必须唯一)
            name: "configStore",
            // 自定义存储(默认localStorage)
            storage: createJSONStorage(() => localStorage),
            // 只存储某个字段
            // partialize: (state) => ({ bears: state.bears, color: state.color }),
            // 不存储某个字段
            partialize: (state) =>
              Object.fromEntries(
                Object.entries(state).filter(
                  ([key]) => !["initSetting"].includes(key)
                )
              ),
          })
        ),
        {
          enabled: true, // 是否启用devtools
          name: "configStore", // devtools名称
        }
      )
    )
  )
);
